#!/usr/bin/env python
# coding=utf-8
import traceback

import hashlib

# 计算文件的md5值
import traceback
import redis
import json

# pool必须是单例的
from requests.adapters import HTTPAdapter

pool = redis.ConnectionPool(host="127.0.0.1", password="",
                            port=6379, max_connections=100, decode_responses=True, encoding="utf8",
                            db=0)  # 创造连接池,最多能放多少链接

# pool_db1 = redis.ConnectionPool(host="192.168.31.143", password="qw123666",
#                                 port=6379, max_connections=100, decode_responses=True, encoding="utf8",
#                                 db=1)  # 创造连接池,最多能放多少链接
#
# pool_db2 = redis.ConnectionPool(host="192.168.31.143", password="qw123666",
#                                 port=6379, max_connections=100, decode_responses=True, encoding="utf8",
#                                 db=2)  # 创造连接池,最多能放多少链接

redis_conn = redis.StrictRedis(connection_pool=pool)  # 取出一个链接


# 默认如果返回结果为空，则默认是缓存三分钟
def util_cache(cache_minute=5):
    def decorator(func):
        def wrapper(*args, **kwargs):
            redis_key = func.__name__ + str(args) + str(kwargs)
            redis_value = redis_conn.get(redis_key)
            if redis_value:
                return json.loads(redis_value).get("data")
            else:
                func_return = func(*args, **kwargs)
                if not func_return:
                    cache_time = 3 * 60
                else:
                    cache_time = cache_minute * 60
                cache_data = json.dumps({"data": func_return}, ensure_ascii=False)
                redis_conn.set(redis_key, cache_data, cache_time)
                return func_return

        return wrapper

    return decorator


def calculation_hash_code(fine_path, type="md5", block_size=5 * 1024):
    """ Support md5(), sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), blake2s(),
    sha3_224, sha3_256, sha3_384, sha3_512, shake_128, and shake_256
    """
    with open(fine_path, 'rb') as file:
        hash = hashlib.new(type, b"")
        while True:
            data = file.read(block_size)
            if not data:
                break
            hash.update(data)
        return hash.hexdigest()


# #####################发送企业微信的消息
import requests
import json
import time


@util_cache(cache_minute=60 * 2 - 10)
def get_access_token():
    # 获取到最新的access_token
    qi_ye_id = "ww1b6fb790a8603be3"
    Secret = "_YplVAHR0xcRQ3kGtNOAMKf7H3lQf53bNvkXaVyPeqo"
    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}".format(ID=qi_ye_id,
                                                                                                SECRET=Secret)
    res = requests.get(url).json()
    access_token = res.get("access_token")
    print(access_token)
    return access_token


@util_cache(cache_minute=30)
def send_qi_ye_wei_xin(content=None, touser=None):
    assert content, Exception("content is  not null")
    if not touser:
        touser = "FangHongJian"
    config_dict = {"qi_ye_wei_xin": {
        "AgentId": "1000002",
        "Secret": "_YplVAHR0xcRQ3kGtNOAMKf7H3lQf53bNvkXaVyPeqo",
        "qi_ye_id": "ww1b6fb790a8603be3"
    }}
    AgentId = config_dict.get("qi_ye_wei_xin").get("AgentId")
    # qi_ye_id = config_dict.get("qi_ye_wei_xin").get("qi_ye_id")
    # Secret = config_dict.get("qi_ye_wei_xin").get("Secret")
    access_token = get_access_token()
    # 发送消息
    url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={ACCESS_TOKEN}".format(
        ACCESS_TOKEN=access_token)
    time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    body = {
        "touser": touser,
        "toparty": "",
        "totag": "",
        "msgtype": "text",
        "agentid": AgentId,
        "text": {
            "content": "时间:\r\n{time_str}\n\r\n内容:\r\n{content_text}".format(
                time_str=time_str,
                content_text=content
            )
        },
        "safe": 0,
        "enable_id_trans": 0,
        "enable_duplicate_check": 0,
        "duplicate_check_interval": 1800
    }
    # 将记录插入到数据库表中
    res = requests.post(url, json.dumps(body)).json()
    return res


# #####################高德地图通过ip获取地理位置开始

gao_de_key = "cff928fb187be6463539756b40183569"


@util_cache(cache_minute=60 * 24)
def get_location_from_ip(ip):
    """
        res = {'status': '1', 'info': 'OK', 'infocode': '10000', 'country': '中国', 'province': '湖北省', 'city': '武汉市',
            'district': '江夏区', 'isp': '中国电信', 'location': '114.313961,30.349045', 'ip': '59.174.227.148'}
    """
    print("#############")
    request_url = "https://restapi.amap.com/v5/ip?ip={ip}&type=4&key=cff928fb187be6463539756b40183569".format(
        ip=str(ip))
    res_s1 = requests.get(request_url).json()
    return res_s1


@util_cache(cache_minute=60 * 24)
def get_location_info(location):
    """
{'info': 'OK',
 'infocode': '10000',
 'regeocode': {'addressComponent': {'adcode': '420111',
                                    'building': {'name': '光谷广场',
                                                 'type': '生活服务;美容美发店;美容美发店'},
                                    'businessAreas': [{'id': '420111',
                                                       'location': '114.396536,30.503694',
                                                       'name': '鲁巷'},
                                                      {'id': '420111',
                                                       'location': '114.409500,30.495205',
                                                       'name': '关山'},
                                                      {'id': '420111',
                                                       'location': '114.414914,30.495456',
                                                       'name': '光谷'}],
                                    'city': '武汉市',
                                    'citycode': '027',
                                    'country': '中国',
                                    'district': '洪山区',
                                    'neighborhood': {'name': [], 'type': []},
                                    'province': '湖北省',
                                    'streetNumber': {'direction': '东北',
                                                     'distance': '2.51263',
                                                     'location': '114.400732,30.504278',
                                                     'number': '1号',
                                                     'street': '步行街南路'},
                                    'towncode': '420111080000',
                                    'township': '关东街道'},
               'formatted_address': '湖北省武汉市洪山区关东街道光谷广场光谷资本大厦'},
 'status': '1'}
    """

    params = {"location": location, "key": gao_de_key}
    query_params_list = []
    for item_k, item_v in params.items():
        query_params_list.append(item_k + "=" + item_v)
    query_params = "&".join(query_params_list)
    request_url = "https://restapi.amap.com/v3/geocode/regeo?" + query_params
    res = requests.get(request_url).json()
    return res


# ##################上传文件到阿里云OSS
# https://oss.console.aliyun.com/overview
import oss2
import os

# from datetime import datetime
import datetime


# def get_md5_01(file_path):
#     md5 = ''
#     if os.path.isfile(file_path):
#         f = open(file_path, 'rb')
#         md5_obj = hashlib.md5()
#         md5_obj.update(f.read())
#         hash_code = md5_obj.hexdigest()
#         f.close()
#         md5 = str(hash_code).lower()
#     return md5


@util_cache(cache_minute=60 * 24 * 15)
def upload_oss(file_path):
    if not os.path.exists(file_path):
        raise FileNotFoundError
    file_name = os.path.split(file_path)[-1]
    a_li_yun_config = {
        "AccessKeyID": "LTAI4G9LvzVUv3LYug6EjyBp",
        "AccessKeySecret": "DHNXClS36PDfeLGdbOsVs8004SC7hp"
    }
    # 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    auth = oss2.Auth(a_li_yun_config.get("AccessKeyID"), a_li_yun_config.get("AccessKeySecret"))
    # Endpoint以杭州为例，其它Region请按实际情况填写。
    bucket = oss2.Bucket(auth, 'https://oss-cn-shanghai.aliyuncs.com', 'jhfwxpp')
    with open(file_path, 'rb') as file_obj:
        date_str = datetime.datetime.now().strftime("%Y_%m_%d")
        oss_path = "media/" + date_str + "/" + file_name
        bucket.put_object(oss_path, file_obj)
    res = {
        "oss_path": "https://jhfwxpp.oss-cn-shanghai.aliyuncs.com/" + oss_path,
    }
    return res


# 把文件上传到ftp服务器上
def upload_ftp():
    pass


# 把文件上传到百度网盘
def upload_bai_du_wang_pan():
    pass


##################上传文件到阿里云OSS

# ##################阿里云发送短信
# 阿里云发送短信
# def oss_send_sms(code, PhoneNumbers):
#     from aliyunsdkcore.client import AcsClient
#     from aliyunsdkcore.request import CommonRequest
#     from aliyunsdkcore.client import AcsClient
#     from aliyunsdkcore.request import CommonRequest
#     a_li_yun_config = {
#         "AccessKeyID": "LTAI4G9LvzVUv3LYug6EjyBp",
#         "AccessKeySecret": "DHNXClS36PDfeLGdbOsVs8004SC7hp"
#     }
#     client = AcsClient(a_li_yun_config.get("AccessKeyID"), a_li_yun_config.get("AccessKeySecret"), 'cn-qingdao')
#     request = CommonRequest()
#     request.set_accept_format('json')
#     request.set_domain('dysmsapi.aliyuncs.com')
#     request.set_method('POST')
#     request.set_protocol_type('https')  # https | http
#     request.set_version('2018-05-01')
#     request.set_action_name('SendSms')
#
#     request.add_query_param('PhoneNumbers', "15827325743")
#     request.add_query_param('SignName', "FANGHJ快跑")
#     request.add_query_param('ContentCode', "SMS_193511224")
#     request.add_query_param('ContentParam', "{\"code\":\"7890\"}")
#
#     response = client.do_action(request)
#     # python2:  print(response)
#     print(str(response, encoding='utf-8'))


def test_music_list_util():
    pass


# 获取往前推的日期
def day_get(days):
    res_date_list = []
    date_now = datetime.datetime.now()
    for i in range(days):
        temp_day = datetime.timedelta(days=days - i - 1)
        item_day = date_now - temp_day
        date_to = datetime.datetime(item_day.year, item_day.month, item_day.day)
        res_date_list.append(date_to)
    res_date_list = [item.strftime("%Y-%m-%d") for item in res_date_list]
    return res_date_list


# 解析文件，路径，文件名，扩展名
def get_file_extract(file_url):
    """
    获取文件路径， 文件名， 后缀名
    :param file_url:
    :return:
    """
    filepath, tmp_file_name = os.path.split(file_url)
    shot_name, extension = os.path.splitext(tmp_file_name)
    return filepath, shot_name, extension


class RequestHelper(object):
    def __init__(self):
        """
        session管理器
        requests.session(): 维持会话,跨请求的时候保存参数
        """
        # 实例化session
        self.session = requests.session()
        self.session.mount('http://', HTTPAdapter(max_retries=2))
        self.session.mount('https://', HTTPAdapter(max_retries=2))

    def send_request(self, method, url, params=None, data=None, json=None, headers=None, cert=None, **kwargs):
        """

        :param method: 请求方式
        :param url: 请求地址
        :param params: 字典或bytes，作为参数增加到url中
        :param data: data类型传参，字典、字节序列或文件对象，作为Request的内容
        :param json: json传参，作为Request的内容
        :param headers: 请求头，字典
        :param kwargs: 若还有其他的参数，使用可变参数字典形式进行传递
        :return:
        """
        # 对异常进行捕获
        try:
            """
            封装request请求，将请求方法、请求地址，请求参数、请求头等信息入参。
            注 ：verify: True/False，默认为True，认证SSL证书开关；cert: 本地SSL证书。如果不需要ssl认证，可将这两个入参去掉
            """
            if cert:
                re_data = self.session.request(method, url, params=params, data=data, json=json, headers=headers,
                                               verify=True, cert=cert, **kwargs)
            else:
                re_data = self.session.request(
                    method, url, params=params, data=data, json=json, headers=headers, verify=False, **kwargs)
        # 异常处理 报错显示具体信息
        except Exception as e:
            # 打印异常
            print("请求失败：{0}".format(e))
            raise e
        # 返回响应结果
        return re_data


if __name__ == "__main__":
    # content_str = """同一个签名，1对同一个手机号的发送频率133333333333分钟内短信发送条数不超过：11小时内短信发送条数不超过：51个自然日内短信发送条数不超过：10"""
    # send_qi_ye_wei_xin(content_str)
    # import os
    #
    # zp_dir = os.path.join("D:/tools/zp/zp")
    # content_str = ""
    # for root, dirs, files in os.walk(zp_dir):
    #     files.sort(key=lambda x: int(x.split(".")[0]))
    #     for item_file in files:
    #         file_path = os.path.join(root, item_file)
    #         res = upload_oss(file_path)
    #
    #         temp_str = """<img width="100%" src="{path}">""".format(path=res.get("oss_path"))
    #         print(temp_str)
    # print(files)
    # pass

    # upload_oss()

    print(day_get(3))
